<template>
  <div ref="echartRef" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, markRaw, watch, computed } from 'vue'
import { init } from 'echarts'
import autoHover from '@/utils/echartsTools'

const echartRef = ref(null)

const props = defineProps({
  option: {
    type: Object,
    default: () => {},
  },
  height: {
    type: String,
    default: '100%',
  },
  width: {
    type: String,
    default: '100%',
  },
  // 滚动的数量
  carouselNum: {
    type: Number,
    default: 1,
  },
})

let myChart = null
let timer = null

const initChart = () => {
  if (!myChart) {
    myChart = init(echartRef.value)
  }
  myChart.setOption(props.option, false)
}

// 监听页面大小变化改变echart大小
const resizeChart = () => {
  timer = window.setTimeout(() => {
    if (myChart) {
      myChart.resize()
    }
  }, 500)
}

watch(
  props.option,
  () => {
    initChart()
  },
  { deep: true }
)

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
  autoHover(myChart, props.option, props.carouselNum, 1000)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  clearTimeout(timer)
})
</script>

<style scoped lang="scss"></style>
